/*************************************************************************
	> File Name: alarm.c
	> Author: Angel Criss
	> Blog: blog.abbycin.tk 
	> Created Time: Tue 01 Jul 2014 07:32:52 PM CST
 ************************************************************************/
// 利用alarm 为阻塞操作read设置超时
#include"time.h"
void dealing(int sig)
{
    if(sig==SIGALRM)
    {
        printf("Cought SIGALRM\n");
        exit(0);
    }
}

int main(int argc,char *argv[])
{
    if(argc<2)
    {
        printf("%s time\n",argv[0]);
        printf("input string little than 100 characters: ");
        _exit(0);
    }

    struct sigaction act;
    char input[100];  // declare a pointer to store string

    sigemptyset(&act.sa_mask);
    act.sa_flags=0;
    act.sa_handler=dealing;
    
    if(sigaction(SIGALRM,&act,NULL)==-1)
    {
        perror("sigaction_alarm");
        _exit(errno);
    }

    alarm(atoi(argv[1])); // use argv[1] set wait time

    if(read(STDIN_FILENO,input,99)==-1) //read from STDIN only accept 99 characters
    {
        perror("read");
        _exit(errno);
    }

    alarm(0); // delete alarm

    printf("this input is: %s\n",input);
    exit(0);
}
